/**
 * get 、post 、 delete 接口请求封装
 */
import axios from 'axios'; // 引入axios
import { Message } from 'element-ui';
import router from '@/router/index.js'
import { reject, resolve } from 'core-js/fn/promise';

const PREFIX = '/bms'

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
	return new Promise((resolve, reject) => {
		axios.get(PREFIX + url, {
			params: params
		}).then(res => {
      let resData = res.data
      
      if(resData.code != 200){
        reject(resData)
      } else {
        resolve(resData)
      }
		}).catch(err => {

      let errData = err.response.data

      if(errData.code === 'B962' || errData.code === 'B963'){
        Message.error(errData.message);
        localStorage.removeItem("token")
        router.push('/login');
      } else {
        reject(errData)
      }

		})
	});
}

/** 
 * post方法，对应post请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} params [请求时携带的参数] 
 */
export function post(url, params) {
	return new Promise((resolve, reject) => {
		axios.post(PREFIX + url, params)
			.then(res => {
				let resData = res.data

        if(resData.code != 200){
          reject(resData)
        } else {
          resolve(resData)
        }
			})
			.catch(err => {
        let errData = err.response.data

        if(errData.code === 'B962' || errData.code === 'B963'){
          Message.error(errData.message);
          localStorage.removeItem("token")
          router.push('/login');
        } else {
			  	reject(errData)
        }
			})
	});
}



/** 
 * post方法，对应post请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} params [请求时携带的参数] 
 */
 export function downloadFile(url, params) {

  const ab2str = (u,f) => {
    var b = new Blob([u]);
    var r = new FileReader();
    r.readAsText(b, 'utf-8');
    r.onload = function (){if(f)f.call(null,r.result)}
  }

  return new Promise((resolve,reject) => {

    params['responseType'] = 'blob';
    axios.get(PREFIX + url, {
      'responseType' : 'blob',
			params: params
		}).then(res => {

        resolve(res);
        const content = res.data;
        let reader = new FileReader();
        reader.readAsArrayBuffer(content.slice(0,1));
        reader.onload = evt => {  

            if(evt.target.readyState == FileReader.DONE) {   
              const buffer = evt.target.result; 
              var dv = new DataView(buffer);
              //从第1个字节读取一个8位无符号整数
              var clen = dv.getUint8(0);
              ab2str(content.slice(1,clen +1),title=>{
                  const blob = new Blob([content.slice(clen +1,content.size)]);
                  const fileName = title;
                  resolve(title ,blob);
                  if ('download' in document.createElement('a')) { // 非IE下载
                      const elink = document.createElement('a')
                      elink.download = fileName
                      elink.style.display = 'none'
                      elink.href = URL.createObjectURL(blob)
                      document.body.appendChild(elink)
                      elink.click()
                      URL.revokeObjectURL(elink.href) // 释放URL 对象
                      document.body.removeChild(elink)
                  } else { // IE10+下载
                      navigator.msSaveBlob(blob, fileName)
                  }
              });
            }
        }
    }).catch(err => {
      let errData = err.response.data

      if(errData.code === 'B962' || errData.code === 'B963'){
        Message.error(errData.message);
        localStorage.removeItem("token")
        router.push('/login');
      } else {
        reject(errData)
      }

    });
  });

}